package cn.threewaters.qtyy.tools.gitmake;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * @ClassName: GitFileMake
 * 
 * @Description: 由于git对空文件夹自动忽略变更差异，所以开发此工具类对项目中空文件夹建立.keep文件，保证所有文件夹能完整上传，
 * 
 *               保证项目的结构
 * 
 * @author Waters
 * 
 * @date 2016年6月29日 下午11:54:57
 * 
 */
public class GitFileMake {

	public static final String FILENAME = ".keep";
	public static final String LOGDIR = "gitlog";
	public static final String PROJECTNAME = "qtyy";
	public static final String FILENEW = "建立";
	public static final String FILEDELETE = "删除";

	public static String LOGFILENAME = "git{TIME}.log";
	private static int index = 0;

	public static void main(String[] args) throws Exception {
		FileWriter writer = new FileWriter(getLogFile(), true);
		writer.write(log(index, "开始", ""));
		make(getProjectFile(), writer);
		writer.write(log(index, "结束", ""));
		writer.close();
	}

	/**
	 * make(文件处理：建立文件，删除文件)
	 * 
	 * @Title: make
	 * 
	 * @return void 返回类型
	 * 
	 */
	public static void make(File projectFile, FileWriter writer) throws Exception {
		// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
		if (projectFile.getAbsolutePath().indexOf(".git") != -1) {
			return;
		}
		if (projectFile.isDirectory()) {
			File[] listFiles = projectFile.listFiles();
			if (listFiles.length == 0) {
				// 创建文件

				File keep = new File(projectFile.getAbsolutePath() + "\\" + FILENAME);
				keep.createNewFile();
				FileWriter keepWriter = new FileWriter(keep);
				keepWriter.write("此文件用于github空文件夹占位处理");
				keepWriter.close();
				index++;
				writer.write(log(index, FILENEW, keep.getAbsolutePath()));
			} else {
				for (File f : listFiles) {
					if (listFiles.length > 1 && f.getName().equals(FILENAME)) {
						index++;
						writer.write(log(index, FILEDELETE, f.getAbsolutePath()));
						f.delete();
					}
					if (f.isDirectory()) {
						make(f, writer);
					}
				}
			}
		}
	}

	/**
	 * log(记录日志文件)
	 * 
	 * @Title: log
	 * 
	 * @return String 返回类型
	 */
	public static String log(int index, String type, String content) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append(String.format("%05d", index));
		sb.append("[");
		sb.append(type);
		sb.append("]");
		sb.append("[");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sb.append(dateFormat.format(new Date()));
		sb.append("]");
		sb.append("[");
		sb.append(InetAddress.getLocalHost().getHostAddress());
		sb.append("::");
		byte[] mac = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
		StringBuilder macsb = new StringBuilder();
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				macsb.append("-");
			}
			int temp = mac[i] & 0xff;
			String str = Integer.toHexString(temp);
			if (str.length() == 1) {
				macsb.append("0" + str);
			} else {
				macsb.append(str);
			}
		}
		sb.append(macsb.toString().toUpperCase());
		sb.append("]");
		sb.append("[");
		sb.append(System.getenv().get("COMPUTERNAME"));
		sb.append("::");
		sb.append(System.getenv().get("USERNAME"));
		sb.append("]");
		sb.append("[");
		sb.append(content);
		sb.append("]\r\n");
		System.out.print(sb.toString());
		return sb.toString();
	}

	/**
	 * getLogFile(获取日志文件路径)
	 *
	 * @Title: getLogFile
	 * 
	 * @return File 返回类型
	 */
	public static File getLogFile() throws IOException {
		File projectFile = getProjectFile();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		LOGFILENAME = LOGFILENAME.replace("{TIME}", dateFormat.format(new Date()));
		File dir = new File(projectFile.getPath() + "/" + LOGDIR + "/");
		if (!dir.exists()) {
			dir.mkdir();
		}
		File file = new File(projectFile.getPath() + "/" + LOGDIR + "/" + LOGFILENAME);
		if (!file.exists()) {
			System.out.println(file.getAbsolutePath());
			file.createNewFile();
		}
		return file;
	}

	/**
	 * getProjectFile(获取项目所在路径)
	 * 
	 * @Title: getProjectFile
	 * 
	 * @return File 返回类型
	 */
	public static File getProjectFile() {
		int beginIndex = 5;
		String osName = System.getProperties().getProperty("os.name");
		if (osName.toUpperCase().startsWith("WIN")) {
			beginIndex = 6;
		}
		String path = GitFileMake.class.getResource("").toString();
		if (path != null) {
			// 20160701张淼：由于项目名称可能存在与路径中某单词重名，所以增加过滤选项

			path = path.substring(beginIndex, path.indexOf("/" + PROJECTNAME) + PROJECTNAME.length() + 1);
		}
		System.out.println(path);
		return new File(path);
	}
}
